import MimeWriter
import mimetools
import cStringIO
import smtplib
from ats.log import logger

def send_email(sender, recipiant, subject, msg, smptserver='localhost', ishtml=0):
	""" sends an email. 
	"""
	log = logger.get_logger()
	try:
		if not ishtml:
			msg = "Subject:%s\n\n%s" % (subject, msg)
		server = smtplib.SMTP(smptserver)
		server.sendmail(sender, recipiant, msg)
		server.quit()
		return 1
	except Exception, e:
		log.error("Error sending email: \n%s" % e)
		return 0

def send_html_email(sender, recipiant, subject, html, text,smtpserver='localhost'):
	""" creates + sends an html email
	"""
	return send_email(
		sender, 
		recipiant, 
		subject, 
		createhtmlmail(html,text,subject,recipiant,sender),
		smtpserver,
		1)

def createhtmlmail (html, text, subject,recipient,sender):
	"""Create a mime-message that will render HTML in popular
		MUAs, text in better ones"""
	import MimeWriter
	import mimetools
	import cStringIO
	
	out = cStringIO.StringIO() # output buffer for our message 
	htmlin = cStringIO.StringIO(html)
	txtin = cStringIO.StringIO(text)
	writer = MimeWriter.MimeWriter(out)

	#
	# set up some basic headers... we put subject here
	# because smtplib.sendmail expects it to be in the
	# message body
	#
	writer.addheader("Subject", subject)
	writer.addheader("MIME-Version", "1.0")
	writer.addheader("From", sender)
	writer.addheader("To", recipient)
	#
	# start the multipart section of the message
	# multipart/alternative seems to work better
	# on some MUAs than multipart/mixed
	#
	writer.startmultipartbody("alternative")
	writer.flushheaders()
	#
	# the plain text section
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
	mimetools.encode(txtin, pout, 'quoted-printable')
	txtin.close()
	#
	# start the html subpart of the message
	#
	subpart = writer.nextpart()
	subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
	#
	# returns us a file-ish object we can write to
	#
	pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
	mimetools.encode(htmlin, pout, 'quoted-printable')
	htmlin.close()
	#
	# Now that we're done, close our writer and
	# return the message body
	#
	writer.lastpart()
	msg = out.getvalue()
	out.close()
	#print msg
	return msg
